package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"fmt"
	"strconv"
)

var jrebelPrivateKey = `-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDQ93CP6SjEneDizCF1P/MaBGf582voNNFcu8oMhgdTZ/N6qa6O7XJDr1FSCyaDdKSsPCdxPK7Y4Usq/fOPas2kCgYcRS/iebrtPEFZ/7TLfk39HLuTEjzo0/CNvjVsgWeh9BYznFaxFDLx7fLKqCQ6w1OKScnsdqwjpaXwXqiulwIDAQABAoGATOQvvBSMVsTNQkbgrNcqKdGjPNrwQtJkk13aO/95ZJxkgCc9vwPqPrOdFbZappZeHa5IyScOI2nLEfe+DnC7V80K2dBtaIQjOeZQt5HoTRG4EHQaWoDh27BWuJoip5WMrOd+1qfkOtZoRjNcHl86LIAh/+3vxYyebkug4UHNGPkCQQD+N4ZUkhKNQW7mpxX6eecitmOdN7Yt0YH9UmxPiW1LyCEbLwduMR2tfyGfrbZALiGzlKJize38shGC1qYSMvZFAkEA0m6psWWiTUWtaOKMxkTkcUdigalZ9xFSEl6jXFB94AD+dlPS3J5gNzTEmbPLc14VIWJFkO+UOrpl77w5uF2dKwJAaMpslhnsicvKMkv31FtBut5iK6GWeEafhdPfD94/bnidpP362yJl8Gmya4cI1GXvwH3pfj8S9hJVA5EFvgTB3QJBAJP1O1uAGp46X7Nfl5vQ1M7RYnHIoXkWtJ417Kb78YWPLVwFlD2LHhuy/okT4fk8LZ9LeZ5u1cp1RTdLIUqAiAECQC46OwOm87L35yaVfpUIjqg/1gsNwNsj8HvtXdF/9d30JIM3GwdytCvNRLqP35Ciogb9AO8ke8L6zY83nxPbClM=
-----END RSA PRIVATE KEY-----`
var serverRandomness = "H2ulzLlh7E0="
var serverGUID = "da3ae944-a101-4f53-acc3-8aeb8c834573"

func signLicense(clientRandomness string, guid string, offline bool, validFrom interface{}, validUntil interface{}) string {
	// 拼接字符串,用 ; 分割
	// lientRandomness, serverRandomness, guid, String.valueOf(offline)
	var licenseString string
	if offline {
		licenseString = fmt.Sprintf("%s;%s;%s;%s;%d;%d", clientRandomness, serverRandomness, guid, strconv.FormatBool(offline), validFrom, validUntil)
	} else {
		licenseString = fmt.Sprintf("%s;%s;%s;%s", clientRandomness, serverRandomness, guid, strconv.FormatBool(offline))
	}

	// 开始签名
	block, _ := pem.Decode([]byte(jrebelPrivateKey))
	private, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		panic(err)
	}
	h := crypto.Hash.New(crypto.SHA1) //进行SHA1的散列
	h.Write([]byte(licenseString))
	hashed := h.Sum(nil)

	// 进行rsa加密签名
	signedData, err := rsa.SignPKCS1v15(rand.Reader, private, crypto.SHA1, hashed)
	encoded := base64.StdEncoding.EncodeToString(signedData)
	return encoded
}
